// 获取应用实例
const app = getApp();

const z = require("../../../utils/util");

// 初始化数据库
const db = wx.cloud.database();
const message = db.collection("message");
const uimg = db.collection("uimg");
// const cnm = db.collection("cnm");

// pages/addmsg/addmsg.js
import dayjs from "dayjs";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    theme: 1,
    switch: false,
    // msgList: [],
    addContent: "",
    // initID: 99,
    disabled: false,
    fileID: "",
    openid: "",
    o_openid: "",
    msgList: [],
    heartbeat_value: 0,

    navHeight: app.globalData.navBarHeight,
    menuHeight: app.globalData.menuHeight,
    menuRight: app.globalData.menuRight,
    menuTop: app.globalData.menuTop,

    fileList: [],
  },

  // 获取数据
  getMsgData() {
    const { openid } = this.data;
    message.where({ _openid: openid }).get({
      success: (res) => {
        this.setData({
          msgList: res.data[0].myMsg,
        });
      },
    });
    uimg.where({ _openid: openid }).get({
      success: (res) => {
        this.setData({
          heartbeat_value: res.data[0].heartbeat_value,
        });
      },
    });
  },

  afterRead(event) {
    var that = this;
    const { fileList } = that.data;
    const { file } = event.detail;

    // 封装上传图片
    z.uploadFile(
      () => {
        that.setData({
          disabled: true,
        });
      },
      file.url,
      "message",
      (url, fileId) => {
        fileList.push({
          url,
          fileId,
        });
        that.setData({
          fileList,
          disabled: false,
        });
      },
      () => { }
    );
  },

  // 删除图片
  delete(e) {
    const that = this;
    let { fileList } = that.data;
    const { url, fileId } = e.detail.file;
    wx.showModal({
      title: "删除提示",
      content: "确定要删除该图片嘛？",
      success: (result) => {
        if (result.confirm) {
          fileList = fileList.filter((i) => i.url != url);
          this.setData({ fileList });
          wx.cloud.deleteFile({
            fileList: [fileId],
            success(res) {
              console.log(res, "删除文件");
            },
            fail(err) {
              console.log(err);
            },
          });
        }
      },
      fail: () => { },
      complete: () => { },
    });
  },

  // 获取输入内容
  inputstr(e) {
    var name = e.detail.value;
    this.setData({
      addContent: name,
    });
  },

  // 添加留言
  addMsg() {
    const that = this;
    let { addContent, fileList, disabled, openid, msgList, heartbeat_value } = this.data;
    if (disabled) {
      wx.showToast({
        title: "图片上传中",
        icon: "error",
      });
      return;
    }
    if (addContent == "") {
      wx.showToast({
        title: "请输入内容",
        icon: "error",
      });
    } else {
      msgList.unshift({
        content: addContent,
        images: fileList,
        time: dayjs(new Date()).format("YYYY/MM/DD HH:mm:ss"),
        comment: [],
        // nickname: wx.getStorageSync("nickname") || "",
        // avatarUrl: wx.getStorageSync("avatarUrl") || "",
      });
      message.where({ _openid: openid }).update({
        data: {
          myMsg: msgList,
          nickname: wx.getStorageSync("nickname") || "",
          avatarUrl: wx.getStorageSync("avatarUrl") || "",
        },
        success: function (res) {
          wx.showToast({
            title: "发布成功",
            icon: "success",
          });
          that.setData({ fileList: [], addContent: '' })
          heartbeat_value += 2;
          uimg.where({ _openid: openid }).update({
            data: {
              heartbeat_value
            },
            success: (res) => { },
            fail: (err) => { },
          })
        },
        fail: (err) => {
          wx.showToast({
            title: "发布失败",
            icon: "error",
          });
        },
      });
      z.subscribe(2, '发布“动态”所增加心动值', true);
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) { },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const that = this;
    const openid = wx.getStorageSync("openid");
    const o_openid = wx.getStorageSync("o_openid");
    that.setData({
      theme: app.globalData.theme,
      switch: app.globalData.switch,
      openid,
      o_openid
    });

    this.getMsgData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    const that = this;
    let { fileList } = that.data;
    fileList.forEach(i => {
      wx.cloud.deleteFile({
        fileList: [i.fileId],
        success(res) {
          console.log(res, "删除文件");
        },
        fail(err) {
          console.log(err);
        },
      });
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() { },
});
